import time

from osv import osv, fields
from osv.orm import intersect


class kdvn_received(osv.osv):
    _description="KDVN Received"
    _name="kdvn.received"
    
    def _onchange_amount(self, cr, uid, ids,amount_tax,amount,actual_tax,actual_amount,rate=False):
#        total_amount=(amount or 0)+(amount_tax or 0)
#        actual_total=(actual_amount or 0)+(actual_tax or 0)
        if rate:
            actual_tax=amount_tax*rate
            actual_amount=amount*rate
            val={'actual_total_amount':actual_tax+actual_amount,
                 'actual_tax_amount':actual_tax,
                 'actual_amount':actual_amount,
                 }
        else:            
            if actual_amount:
                if amount==0:
                    val={'rate':0}
                else:
                    tax_percent=amount_tax/amount
                    actual_tax=actual_amount*tax_percent
                    actual_total=actual_tax+actual_amount
                    rate=actual_total/(amount_tax+amount)
                    val={'actual_total_amount':actual_total,
                         'actual_tax_amount':actual_tax,
                         'rate':rate}
            elif actual_tax:
                actual_total=actual_tax+actual_amount
                rate=actual_total/(amount_tax+amount)
                val={'actual_total_amount':actual_total,
                     'rate':rate}
            else:
                if amount_tax+amount==0:
                    val={'total_amount':amount_tax+amount,
                     'rate':(actual_tax+actual_amount)/(amount_tax+amount)}
                else:
                    val={'total_amount':amount_tax+amount,
                     'rate':0}
        return {'value':val}
    
    def _get_currency(self,cr,uid,ids,name,arg,context={}):
        res = {}
        if ids:
            acc_set = ",".join(map(str, ids))
            cr.execute("Select kr.id,contract_currency_id from kdvn_payment_from_client kpfc left join \
                            kdvn_received kr on kpfc.id=kr.payment_id where kr.id in (%s) " % acc_set)
            for kr_id, curr_id in cr.fetchall():
                res[kr_id] = curr_id
            for obj_id in ids:
                res.setdefault(obj_id, 0)
            for id in ids:
                res[id] = res.get(id,0)
        return res
    
    def _new_received(self, cr, uid, context={}):
        this_time=0
        if context:
            if 'claim_id' in context:
                #pfc_obj=self.pool.get('kdvn.payment.from.client')
                kdvn_received_ids=self.search(cr,uid,[('payment_id','=',context['claim_id'])])
                received=0.0
                claim_amount=0.0
                if 'claim_amount' in context:
                    claim_amount=context['claim_amount']
                if kdvn_received_ids:
                    kdvn_received_lists=self.read(cr,uid,kdvn_received_ids,['amount'],context)
                    for krl in kdvn_received_lists:
                        received+=krl['amount']
                this_time=claim_amount-received
        return this_time

    def _new_received_total(self, cr, uid, context={}):
        this_time=0
        if context:
            if 'claim_id' in context:
                #pfc_obj=self.pool.get('kdvn.payment.from.client')
                kdvn_received_ids=self.search(cr,uid,[('payment_id','=',context['claim_id'])])
                received=0.0
                claim_amount=0.0
                amount_tax=0.0
                if 'amount_tax' in context:
                    amount_tax=context['amount_tax']
                if 'claim_amount' in context:
                    claim_amount=context['claim_amount']
                if kdvn_received_ids:
                    kdvn_received_lists=self.read(cr,uid,kdvn_received_ids,['amount','tax_amount'],context)
                    for krl in kdvn_received_lists:
                        received+=krl['amount'] + krl['tax_amount']
                this_time=claim_amount+amount_tax-received
        return this_time
    
    def _new_received_vat(self, cr, uid, context={}):
        this_time=0
        if context:
            if 'claim_id' in context:
                #pfc_obj=self.pool.get('kdvn.payment.from.client')
                kdvn_received_ids=self.search(cr,uid,[('payment_id','=',context['claim_id'])])
                received=0.0
                amount_tax=0.0
                if 'amount_tax' in context:
                    amount_tax=context['amount_tax']
                if kdvn_received_ids:
                    kdvn_received_lists=self.read(cr,uid,kdvn_received_ids,['tax_amount'],context)
                    for krl in kdvn_received_lists:
                        received+=krl['tax_amount']
                this_time=amount_tax-received
        return this_time

    def _get_currency_def(self, cr, uid, context={}):
        get_curr=False
        if context:
            if 'claim_id' in context:
                pfc_obj = self.pool.get('kdvn.payment.from.client')
                pfc_currency = pfc_obj.read(cr,uid,context['claim_id'],['contract_currency_id'])
    #            fo=open("/home/openerp/a.txt","w")
    #            fo.write(str(pfc_currency))
    #            fo.close()
                if pfc_currency:
                    get_curr = pfc_currency['contract_currency_id'][0]
        return get_curr
    
    def _rate(self,cr,uid,ids,name,arg,context={}):
        res={}
        for kr in self.browse(cr,uid,ids):
            if kr.amount==0:
                res[kr.id]=0
            else:
                res[kr.id]=kr.actual_amount/kr.amount
        for id in ids:
            res[id]=res.get(id,0)
        return res
    
    def _get_total(self,cr,uid,ids,name,arg,context={}):
        res={}
        for kr in self.browse(cr,uid,ids):
#            if not kr.amount:
#                kramount = 0
#            else:
#                kramount=kr.amount
#            if not kr.tax_amount:
#                krtax_amount = 0
#            else:
#                krtax_amount = kr.tax_amount
            res[kr.id]={'total_amount':(kr.amount or 0) + (kr.tax_amount or 0),
                        'actual_total_amount':(kr.actual_amount or 0) + (kr.actual_tax_amount or 0)}
        return res
     
    _columns={
              'payment_id':fields.many2one('kdvn.payment.from.client','Payment ID'),
              'date':fields.date('Date'),
              'currency_id':fields.function(_get_currency,method=True,type="many2one",relation="project.currency",string="Currency"),
              'amount':fields.float('Amount'),
              'tax_amount':fields.float('Tax'),
              'recv_cur':fields.selection([('VND','VND'),('USD','USD')],'Recv. Cur.'),
              'total_amount':fields.function(_get_total,method=True,string='Total',multi='total',type='float',digits=(16,2)),
              'actual_amount':fields.float('Equivalent in Default'),
              'rate':fields.float('@'),
              'actual_tax_amount':fields.float('Tax'),
              'actual_total_amount':fields.function(_get_total,method=True,string='Total in VND',multi='total',type='float',digits=(16,2))
              }
    _defaults = {
                 'date':lambda *a:time.strftime('%Y-%m-%d'),
                 'amount':_new_received,
                 'currency_id':_get_currency_def,
                 'tax_amount':_new_received_vat,
                 'total_amount':_new_received_total,
                 'recv_cur':lambda *a:'VND'
                 }
kdvn_received()


#class kdvn_contract_client(osv.osv):
#    _name = "kdvn.contract.client"
#    _description="KDVN Contract Client"
#    _inherit = "kdvn.contract.client"
#
#    def _compute_lines(self, cr, uid, ids, name, args, context=None):
#        mresult={}
#        for prj in ids:
#            mresult[prj]=[]
#            ids2 = self.search(cr, uid, [('parent_id', 'child_of', [prj])])
#            cr.execute("Select kr.id as payment_id \
#                            from account_invoice ai left join kdvn_received kr \
#                            on ai.id=kr.invoice_id where kr.id>0 and project_id in ("+ ','.join([str(x) for x in ids2]) + ')')
#            mresult[prj] = [x[0] for x in cr.fetchall()]
#        return mresult
#    
#    _columns = {
#                'payment_ids': fields.function(_compute_lines, method=True, relation='kdvn.received', type="one2many", string='Payments'),
#                }
#kdvn_contract_client()